<?

/**
 * DevSuite
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://suite.rapidcodefactory.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@rapidcodefactory.com so we can send you a copy immediately.
 *
 * @category   RFC_Model
 * @package    RCF_DModel
 * @copyright  Copyright (c) 2010-2011 Rapid Code Factory Ltd. POLAND (http://www.rapidcodefactory.com)
 * @license    http://suite.rapidcodefactory.com/license/new-bsd     New BSD License
 * @version    
*/



/**
 * Class for DB_Object Model
 *
 * @category   RFC_Model
 * @package    RFC_DModel
 * @copyright  Copyright (c) 2010-2011 Rapid Code Factory Ltd. POLAND (http://www.rapidcodefactory.com)
 * @license    http://suite.rapidcodefactory.com/license/new-bsd     New BSD License
*/

require_once('Files.php');
require_once('Statuses.php');
require_once('Users.php');
require_once('Categories.php');
require_once('OffersTypes.php');

class Offers extends DomainModel {
	protected $id;	//primaryKey=yes, dataType=int, maxLength=, allowNulls=no
	protected $appsId;	//primaryKey=no, dataType=int, maxLength=, allowNulls=no
	protected $usersId;	//primaryKey=no, dataType=int, maxLength=, allowNulls=no
	protected $statusesId;	//primaryKey=no, dataType=int, maxLength=, allowNulls=no
	protected $offersTypesId;	//primaryKey=no, dataType=int, maxLength=, allowNulls=no
	protected $categoriesId;	//primaryKey=no, dataType=int, maxLength=, allowNulls=no
	protected $mainImageId;	//primaryKey=no, dataType=int, maxLength=, allowNulls=yes
	protected $title;	//primaryKey=no, dataType=varchar, maxLength=200, allowNulls=yes
	protected $teaser;	//primaryKey=no, dataType=varchar, maxLength=300, allowNulls=yes
	protected $description;	//primaryKey=no, dataType=varchar, maxLength=1500, allowNulls=yes
	protected $instruction;	//primaryKey=no, dataType=varchar, maxLength=1500, allowNulls=yes
	protected $tags;	//primaryKey=no, dataType=varchar, maxLength=500, allowNulls=yes
	protected $addDate;	//primaryKey=no, dataType=datetime, maxLength=, allowNulls=yes
	protected $expireDate;	//primaryKey=no, dataType=datetime, maxLength=, allowNulls=yes
	protected $price;	//primaryKey=no, dataType=double, maxLength=, allowNulls=no
	protected $requireShipping;	//primaryKey=no, dataType=smallint, maxLength=, allowNulls=no
	protected $shippingPrice;	//primaryKey=no, dataType=float, maxLength=, allowNulls=no
	protected $realizationDays;	//primaryKey=no, dataType=smallint, maxLength=, allowNulls=yes
	protected $countrySelected;	//primaryKey=no, dataType=varchar, maxLength=75, allowNulls=yes
	protected $additionaShippingPrice;	//primaryKey=no, dataType=float, maxLength=, allowNulls=no
	
	protected $mainImage;
	protected $config;
	protected $status;
	protected $files;
	protected $type;
	protected $user;
	protected $category;
	protected $rating;
	protected $popularity;
	
	public function getConfig(){
		if (is_null($this->config)){
			$registry = Zend_Registry::getInstance();
			$config = $registry->get('config');
			$this->config = $config->uploads->offers;
		}
		
		return $this->config;
	}
	
	public function getMainImage(){
		if (is_null($this->mainImage)){
			$this->mainImage = ModelMapper::instance('Files')->find($this->mainImageId);
		}
		
		return $this->mainImage;
	}
	
	public function getImageUrl(){
		if (!is_null($this->mainImageId)){
			return $this->getConfig()->origin_dir.'/'.$this->getMainImage()->getId().'.'.$this->getMainImage()->getExtension();
		}
		
	}
	
	function getThumb($width = '100', $height = '70'){
		if ($width == ''){
			$width = $this->getConfig()->thumbWidth;
		}
			
		if ($height == ''){
			$height = $this->getConfig()->thumbHeight;
		}
		
		if ($this->mainImageId != null && $this->getMainImage() != null){
			$image = '<img src="'.$this->getMainImage()->createThumb($this->getConfig()->origin_dir, $width, $height).'" border="0" class="'.$this->getConfig()->cssId.'" />';
		} else {
			$tExt = 'png';
			$tClass = $this->getConfig()->cssId;
			$image = DataUtils::genThumb($width, $height, $this->getConfig()->no_file_image, $tClass, $tExt);
		}
		return $image;
	}
	
	public function getStatus(){
		if (is_null($this->status)){
			$this->status = ModelMapper::instance('Statuses')->find($this->statusesId);
		}
		
		return $this->status;
	}
	
	public function getType(){
		if (is_null($this->type)){
			$this->type = ModelMapper::instance('OffersTypes')->find($this->offersTypesId);
		}
		
		return $this->type;
	}
	
	public function getUser(){
		if (is_null($this->user)){
			$this->user = ModelMapper::instance('Users')->find($this->usersId);
		}
		
		return $this->user;
	}
	
	public function getCategory(){
		if (is_null($this->category)){
			$this->category = ModelMapper::instance('Categories')->find($this->categoriesId);
		}
		
		return $this->category;
	}
	
	public function getFiles(){
		if (is_null($this->files)){
			$filter = "WHERE object_id = ".$this->id;
			$orderBy = "ORDER BY id ASC";
			$this->files = ModelMapper::instance('Files')->findFiltered($filter, $orderBy);
		}
		
		return $this->files;
	}
	
	public function getTagsToArray(){
		if ($this->tags != '')
			return $array = explode(',',$this->tags);
		else {
			return array();
		}
	}
}




/**
 * Class for DB_Object ModelMapper
 *
 * @category   RFC_Model
 * @package    RFC_DModel
 * @copyright  Copyright (c) 2010-2011 Rapid Code Factory Ltd. POLAND (http://www.rapidcodefactory.com)
 * @license    http://suite.rapidcodefactory.com/license/new-bsd     New BSD License
*/
class OffersMapper extends ModelMapper {
	function __construct(){
		parent::__construct();
		$this->tableName = 'offers';
		$this->selectViewName = 'v_offers';
		$this->selectFields = '
				id,
				apps_id,
				users_id,
				statuses_id,
				offers_types_id,
				categories_id,
				main_image_id,
				title,
				teaser,
				description,
				instruction,
				tags,
				add_date,
				expire_date,
				price,
				require_shipping,
				shipping_price,
				realization_days,
				country_selected,
				additiona_shipping_price,
				rating,
				popularity,
				ot_id,
		        ot_type,
		        st_id,
		        st_statuses_catalogues_id,
		        st_status,
		        st_description,
		        sc_id,
		        sc_catalogue,
		        ct_id,
		        ct_category,
		        ct_weight,
		        ct_level,
		        ct_parent_id,
		        f_id,
		        f_file_types_id,
		        f_object_id,
		        f_name,
		        f_size,
		        f_extension,
		        f_type,
		        f_users_id,
		        f_add_date,
		        f_description,
		        ft_id,
		        ft_type,
		        u_id,
		        u_apps_id,
		        u_statuses_id,
		        u_username,
		        u_password,
		        u_first_name,
		        u_last_name,
		        u_email,
		        u_registration_date,
		        u_last_update_date,
		        u_is_administrator,
		        u_is_operator,
		        u_system_roles_id
		';

		$this->findQuery = self::$DB->prepare("
			SELECT ".$this->selectFields."
			FROM ".$this->selectViewName."
			WHERE id = ?
		");
		$this->insertQuery = self::$DB->prepare("
			CALL p_add_offers (@p_id,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?
		)");


		$this->updateQuery = self::$DB->prepare("
			CALL p_upd_offers (
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?

		)");

		$this->deleteQuery = self::$DB->prepare("
			CALL p_del_offers (?)
		");

		$this->cacheTime = null;
	}

	protected function doLoad($array){
		$acuire = str_replace('Mapper', '', get_class($this));
		$obj = new $acuire($array['id']);
		$obj->setId($array['id']);
		$obj->setAppsId($array['apps_id']);
		$obj->setUsersId($array['users_id']);
		$obj->setStatusesId($array['statuses_id']);
		$obj->setOffersTypesId($array['offers_types_id']);
		$obj->setCategoriesId($array['categories_id']);
		$obj->setMainImageId($array['main_image_id']);
		$obj->setTitle($array['title']);
		$obj->setTeaser($array['teaser']);
		$obj->setDescription($array['description']);
		$obj->setInstruction($array['instruction']);
		$obj->setTags($array['tags']);
		$obj->setAddDate($array['add_date']);
		$obj->setExpireDate($array['expire_date']);
		$obj->setPrice($array['price']);
		$obj->setRequireShipping($array['require_shipping']);
		$obj->setShippingPrice($array['shipping_price']);
		$obj->setRealizationDays($array['realization_days']);
		$obj->setCountrySelected($array['country_selected']);
		$obj->setAdditionaShippingPrice($array['additiona_shipping_price']);
		$obj->setRating($array['rating']);
		$obj->setPopularity($array['popularity']);
		
		$arr = ArrayUtils::splitByPrefix($array, array('ot_','st_','f_', 'ft_', 'u_', 'ct_', 'sc_'));
		
		if (!empty($arr['sc_']))
			ModelMapper::instance('StatusesCatalogues')->loadArray($arr['sc_']);
		if (!empty($arr['st_']))
			ModelMapper::instance('Statuses')->loadArray($arr['st_']);
		if (!empty($arr['ot_']))
			ModelMapper::instance('OffersTypes')->loadArray($arr['ot_']);
		if (!empty($arr['f_']))
			ModelMapper::instance('Files')->loadArray($arr['f_']);
		if (!empty($arr['ft_']))
			ModelMapper::instance('FilesTypes')->loadArray($arr['ft_']);
		if (!empty($arr['ct_']))
			ModelMapper::instance('Categories')->loadArray($arr['ct_']);
		if (!empty($arr['u_']))
			ModelMapper::instance('Users')->loadArray($arr['u_']);
		return $obj;
	}

	function insert(DomainModel $obj){

		$values = array(
			$obj->getAppsId(),
			$obj->getUsersId(),
			$obj->getStatusesId(),
			$obj->getOffersTypesId(),
			$obj->getCategoriesId(),
			$obj->getMainImageId(),
			$obj->getTitle(),
			$obj->getTeaser(),
			$obj->getDescription(),
			$obj->getInstruction(),
			$obj->getTags(),
			$obj->getAddDate(),
			$obj->getExpireDate(),
			$obj->getPrice(),
			$obj->getRequireShipping(),
			$obj->getShippingPrice(),
			$obj->getRealizationDays(),
			$obj->getCountrySelected(),
			$obj->getAdditionaShippingPrice()
		);

		$this->doStatement($this->insertQuery, $values);
		$obj->setId(self::$DB->getOne("SELECT @p_id"));
	}

	function update(DomainModel $obj){
		$values = array(
			$obj->getId(),
			$obj->getAppsId(),
			$obj->getUsersId(),
			$obj->getStatusesId(),
			$obj->getOffersTypesId(),
			$obj->getCategoriesId(),
			$obj->getMainImageId(),
			$obj->getTitle(),
			$obj->getTeaser(),
			$obj->getDescription(),
			$obj->getInstruction(),
			$obj->getTags(),
			$obj->getAddDate(),
			$obj->getExpireDate(),
			$obj->getPrice(),
			$obj->getRequireShipping(),
			$obj->getShippingPrice(),
			$obj->getRealizationDays(),
			$obj->getCountrySelected(),
			$obj->getAdditionaShippingPrice()
		);

		$this->doStatement($this->updateQuery, $values);
	}

	function delete(DomainModel $obj){
		$this->doStatement($this->deleteQuery, array($obj->getId()));
	}

	function newId(){

		$row = self::$DB->getRow('SHOW TABLE STATUS LIKE offers');
		return $row['Auto_increment'];

	}
}


/**
 * Class for DB_Object Model
 *
 * @category   RFC_ModelCollection
 * @package    RFC_DModel
 * @copyright  Copyright (c) 2010-2011 Rapid Code Factory Ltd. POLAND (http://www.rapidcodefactory.com)
 * @license    http://suite.rapidcodefactory.com/license/new-bsd     New BSD License
*/
class OffersCollection extends ModelCollection {
	function add(Offers $model){
		$this->doAdd($model);
	}
}


/**
 * Class for DB_Object Model
 *
 * @category   RFC_ModelCollectionExtended
 * @package    RFC_DModel
 * @copyright  Copyright (c) 2010-2011 Rapid Code Factory Ltd. POLAND (http://www.rapidcodefactory.com)
 * @license    http://suite.rapidcodefactory.com/license/new-bsd     New BSD License
*/
class OffersCollectionExtended extends OffersCollection {
	private $stmt;
	private $valueArray;
	private $mapper;
	private $run = false;

	function __construct(ModelMapper $mapper, $stmtHandle, $valueArray){
		parent::__construct();
		$this->stmt = $stmtHandle;
		$this->valueArray = $valueArray;
		$this->mapper = $mapper;
	}

	function notifyAccess(){
		if (!$this->run){
			$result = $this->mapper->doStatement($this->stmt, $this->valueArray,$this->mapper->getCacheTime());
			$this->init_db($result, $this->mapper);
			$this->run = true;
		}
	}
}

?>
